#include "EasyMsgDispatcher.h"
#include "EasyMsg.h"
#include "EasyMsgEventHandler.h"
#include "EasyMsgCallback.h"
namespace EasyMsgImp{

EasyMsgDispatcher* EasyMsgDispatcher::s_instance = nullptr;
EasyMsgDispatcher *EasyMsgDispatcher::Instance()
{
    if(s_instance == nullptr){
        s_instance = new EasyMsgDispatcher();
    }
    return s_instance;
}

EasyMsgDispatcher::EasyMsgDispatcher()
{
    m_eventHandler = new EasyMsgEventHandler();
}

EasyMsgDispatcher::~EasyMsgDispatcher()
{
    delete m_eventHandler;
}

void EasyMsgDispatcher::addCallback(QString msgId, void *hostobj, std::tr1::shared_ptr<EasyMsgCallback> callback)
{
    m_callbackMap[msgId].callbackDataMap[hostobj].append(callback);
}

void EasyMsgDispatcher::removeCallback(QString msgId, void *hostObj)
{
    m_callbackMap[msgId].callbackDataMap.remove(hostObj);
}

void EasyMsgDispatcher::removeCallback(void *hostObj)
{
    QStringList msgLst = m_callbackMap.keys();
    for(QString s : msgLst){
        m_callbackMap[s].callbackDataMap.remove(hostObj);
    }
}

void EasyMsgDispatcher::dispatch(EM::EasyMsg *msg)
{
    if(m_callbackMap.keys().contains(msg->id())){
        QList<QList<std::tr1::shared_ptr<EasyMsgCallback>>> objCallList = m_callbackMap[msg->id()].callbackDataMap.values();
        for(auto callLst : objCallList){
            for(auto p : callLst){
                p->call(msg);
            }
        }
    }
    delete msg;
}

EasyMsgEventHandler *EasyMsgDispatcher::eventHandler()
{
    return m_eventHandler;
}

}
